﻿var WIDGETS = WIDGETS || {};

WIDGETS.button = function ($element) {
    $element = $($element);

    var proto = {
        $element: $element,
        $innerWrapper: $("<i>"),
        cmd: '',
        cmdArgs: '',

        init: function () {
            this.setup();
            this.bindEvents();
        },

        setup: function () {
            this.cmd = this.$element.attr('data-cmd');
            this.cmdArgs = this.$element.attr('data-cmd-args');
            this.$element.wrapInner(this.$innerWrapper);
        },

        bindEvents: function () {
            this.$element.on("tap", this.onClick.bind(this));
            this.$element.on("tapdown", this.setActive.bind(this));
            this.$element.on("tapup", this.removeActive.bind(this));

        },

        onClick: function (ev) {
            if (this.isDisabled())
                return;

            this.toogleSwitch();
            this.triggerCommand();
            this.removeActive();
        },

        setActive: function (ev) {
            if (this.isDisabled())
                return;

            this.$element.addClass("active");
        },

        removeActive: function (ev) {
            this.$element.removeClass("active");
        },

        triggerCommand: function () {
            if (this.cmd) {
                var switchSuffix = "";
                if (this.isSwitch()) {
                    switchSuffix = this.$element.hasClass("on") ? "-on" : "-off"
                }

                var topic = EVENTBROKER.getTopic(this.cmd);
                topic.trigger(this.cmd, this.cmdArgs + switchSuffix);
            }
        },

        isSwitch: function () {
            return this.$element.hasClass('switch');
        },

        toogleSwitch: function () {
            if (!this.isSwitch())
                return;

            this.$element.toggleClass('on');
        },

        setDisabled: function (isDisabled) {
            this.$element.toggleClass('disabled', isDisabled);
        },

        isDisabled: function () {
            return this.$element.hasClass('disabled');
        }
    }

    var inst = $element.data("button");
    if (inst == null) {
        proto.init();
        inst = proto;
        $element.data("button", inst);
    }

    return inst;
}
